<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="40%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="handleClose"
  >
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="图书馆名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="所属学校" prop="school_id">
        <el-select
          v-model="form.school_id"
          placeholder="请选择学校"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="item in schoolOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="form.address" />
      </el-form-item>
      <el-form-item label="位置" prop="location">
        <el-input v-model="form.location" placeholder="例如：经度,纬度" />
      </el-form-item>
      <el-form-item label="开放时间" prop="open_time">
        <el-time-picker
          v-model="form.open_time_picker"
          format="HH:mm"
          placeholder="开放时间"
          style="width: 100%"
          @change="updateOpenTime"
        />
      </el-form-item>
      <el-form-item label="关闭时间" prop="close_time">
        <el-time-picker
          v-model="form.close_time_picker"
          format="HH:mm"
          placeholder="关闭时间"
          style="width: 100%"
          @change="updateCloseTime"
        />
      </el-form-item>
      <el-form-item label="总座位数" prop="total_seats">
        <el-input-number v-model="form.total_seats" :min="0" style="width: 100%" />
      </el-form-item>
      <el-form-item label="图书馆简介" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="4"
          placeholder="请输入图书馆简介"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" style="width: 100%">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { http } from "@/api";

export default {
  name: "LibraryAdd",
  data() {
    return {
      dialogVisible: false,
      dialogTitle: "新增图书馆",
      isEdit: false,
      form: {
        id: undefined,
        name: "",
        school_id: undefined,
        address: "",
        location: "",
        image: "",
        description: "",
        open_time: "",
        close_time: "",
        open_time_picker: null,
        close_time_picker: null,
        total_seats: 0,
        status: 1
      },
      rules: {
        name: [
          { required: true, message: "图书馆名称不能为空", trigger: "blur" },
          { max: 100, message: "图书馆名称不能超过100个字符", trigger: "blur" }
        ],
        school_id: [
          { required: true, message: "请选择所属学校", trigger: "change" }
        ],
        address: [
          { required: true, message: "地址不能为空", trigger: "blur" },
          { max: 255, message: "地址不能超过255个字符", trigger: "blur" }
        ],
        location: [
          { max: 255, message: "位置不能超过255个字符", trigger: "blur" }
        ],
        image: [
          { max: 255, message: "图片URL不能超过255个字符", trigger: "blur" }
        ],
        open_time: [
          { required: true, message: "开放时间不能为空", trigger: "blur" },
          { max: 50, message: "开放时间不能超过50个字符", trigger: "blur" }
        ],
        close_time: [
          { required: true, message: "关闭时间不能为空", trigger: "blur" },
          { max: 50, message: "关闭时间不能超过50个字符", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "change" }
        ]
      },
      schoolOptions: [],
      statusOptions: [
        { label: "开放", value: 1 },
        { label: "关闭", value: 0 }
      ]
    };
  },
  methods: {
    open(row) {
      this.dialogVisible = true;
      this.getSchoolOptions();
      
      if (row) {
        this.isEdit = true;
        this.dialogTitle = "编辑图书馆";
        this.form = { ...row };
        
        // 将时间字符串转换为Date对象用于时间选择器
        if (this.form.open_time) {
          const [hours, minutes] = this.form.open_time.split(':');
          if (hours && minutes) {
            const date = new Date();
            date.setHours(parseInt(hours, 10));
            date.setMinutes(parseInt(minutes, 10));
            this.form.open_time_picker = date;
          }
        }
        
        if (this.form.close_time) {
          const [hours, minutes] = this.form.close_time.split(':');
          if (hours && minutes) {
            const date = new Date();
            date.setHours(parseInt(hours, 10));
            date.setMinutes(parseInt(minutes, 10));
            this.form.close_time_picker = date;
          }
        }
        
        // 确保total_seats是数字
        this.form.total_seats = parseInt(this.form.total_seats || 0, 10);
        
        // 确保status是数字
        this.form.status = parseInt(this.form.status, 10);
      } else {
        this.isEdit = false;
        this.dialogTitle = "新增图书馆";
        this.form = {
          id: undefined,
          name: "",
          school_id: undefined,
          address: "",
          location: "",
          image: "",
          description: "",
          open_time: "",
          close_time: "",
          open_time_picker: null,
          close_time_picker: null,
          total_seats: 0,
          status: 1
        };
      }
      
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },
    
    updateOpenTime(time) {
      if (time) {
        const hours = time.getHours().toString().padStart(2, '0');
        const minutes = time.getMinutes().toString().padStart(2, '0');
        this.form.open_time = `${hours}:${minutes}`;
      } else {
        this.form.open_time = '';
      }
    },
    
    updateCloseTime(time) {
      if (time) {
        const hours = time.getHours().toString().padStart(2, '0');
        const minutes = time.getMinutes().toString().padStart(2, '0');
        this.form.close_time = `${hours}:${minutes}`;
      } else {
        this.form.close_time = '';
      }
    },
    
    getSchoolOptions() {
      http.schools.list().then(response => {
        this.schoolOptions = response.data;
      });
    },
    
    handleClose() {
      this.dialogVisible = false;
      this.$refs.form.resetFields();
    },
    
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            // 移除辅助字段，不发送到后端
            const formData = { ...this.form };
            delete formData.open_time_picker;
            delete formData.close_time_picker;
            
            if (this.isEdit) {
              await http.libraries.update(this.form.id, formData);
              this.$message.success("更新成功");
            } else {
              await http.libraries.create(null, formData);
              this.$message.success("新增成功");
            }
            this.handleClose();
            this.$emit("get-page");
          } catch (error) {
            console.error(error);
            if (error.response && error.response.data && error.response.data.message) {
              this.$message.error(error.response.data.message);
            } else {
              this.$message.error("操作失败，请检查输入是否正确");
            }
          }
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.el-dialog {
  max-height: 90vh;
  overflow: auto;
}
.el-dialog__body {
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}
</style>
